import gzip
import scipy
import sparsesvd
import matplotlib.pyplot as plt

# 从.gz压缩包读取数据到numpy矩阵
file = open("../data/Slashdot0811.txt", "r")
row = []
col = []
data = []
lines = file.readlines()
for line in lines:
    d = line.strip().split("\t")
    row.append(int(d[0]))
    col.append(int(d[1]))
    data.append(1)
m = max(row) + 1 #行数
n = max(col) + 1 #列数
coo_mat = scipy.sparse.coo_matrix((data, (row,col)), shape=(m, n))
csc_mat = coo_mat.tocsc()
print("数据读取完成.")

#svd分解
k = 10
ut, s, vt = sparsesvd.sparsesvd(csc_mat, k)
u = ut.T
print("svd分解完成.")

# 画散点图


fig = plt.figure(figsize=(8,18))

for t in range(2):
    for i in range(k-1):
        fig_num = i + 1 if t == 0 else i + 10
        ax = fig.add_subplot(9, 2, fig_num)
        # 隐藏坐标轴上边和右边
        ax.spines['top'].set_color('none')
        ax.spines['right'].set_color('none')

        # 移动俩个坐标轴
        ax.xaxis.set_ticks_position('bottom')
        ax.spines['bottom'].set_position('center')
        ax.yaxis.set_ticks_position('left')
        ax.spines['left'].set_position('center')

        ax.xaxis.set_ticks_position('bottom')
        ax.yaxis.set_ticks_position('left')


        if t == 0:
            # 设置标题和坐标轴标记
            plt.title("u{}-u{}".format(i + 1, i + 2))
            ax.set_xlabel("u{}".format(i + 1))
            ax.set_ylabel("u{}".format(i + 2))
            ax.xaxis.set_label_coords(1.05, 0.5)
            ax.yaxis.set_label_coords(0.5, 1.05)
            # 填充数据
            ax.scatter(u[:,i], u[:,i+1], s=10)
        else:
            # 设置标题和坐标轴标记
            plt.title("v{}-v{}".format(i + 1, i + 2))
            ax.set_xlabel("v{}".format(i + 1))
            ax.set_ylabel("v{}".format(i + 2))
            ax.xaxis.set_label_coords(1.05, 0.5)
            ax.yaxis.set_label_coords(0.5, 1.05)
            # 填充数据
            ax.scatter(vt[i], vt[i + 1], s=10)


plt.tight_layout()
plt.savefig("question2.png")



